package com.example.projects;

import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;

public class AccessDatabase extends AsyncTask<String, Void, Integer> {
    private Context mContext;
    private ProgressDialog dialog;
    private String barcode;
    private String loc;
    private HttpClient httpClient=null;
    
    public AccessDatabase(Context c) {
            this.mContext = c;
    }
    
    @Override
    protected void onPreExecute() {
            dialog = ProgressDialog.show(this.mContext,
            		"", 
            		"Looking up barcode in product database. Please wait...", 
            		true,
            		true,
            		new DialogInterface.OnCancelListener() {
						
						@Override
						public void onCancel(DialogInterface dialog) {
							AccessDatabase.this.cancel(true);
							finish();
						}
					});
    }
    
    private void finish() {
    	safeClose(httpClient);
    	Intent intent = null;
    	if(loc == "main"){
            intent = new Intent(mContext, Main.class);
    	}
    	if(loc == "comment"){
            intent = new Intent(mContext, Information.class);
    	}
        if(loc == "mcomment"){
        	intent = new Intent(mContext, Information.class);
        }
        //send contents(the barcode) to the product class
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("com.example.projects.MESSAGE", barcode);
        mContext.startActivity(intent);
    }
    
    @Override
    protected void onPostExecute(Integer r) {
    	safeClose(httpClient);
    	AlertDialog.Builder alertBuilder = new AlertDialog.Builder(mContext);
    	alertBuilder
    		.setTitle("Error")
    		.setCancelable(false)
    		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();							
				}
			});
    	AlertDialog alert;
            dialog.dismiss();
            switch(r) {
            case 0: 
            	Intent intent = null;
            	if(loc == "main"){
		            intent = new Intent(mContext, Information.class);
            	}
            	if(loc == "comment"){
		            intent = new Intent(mContext, Comment.class);
            	}
	            if(loc == "mcomment"){
	            	intent = new Intent(mContext, MComment.class);
	            }
	            //send contents(the barcode) to the product class
	            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	            intent.putExtra("com.example.projects.MESSAGE", barcode);
	            mContext.startActivity(intent);
	            break;
            case 1: 
	            alertBuilder.setMessage("Could not connect to product database.  Try again later.");
	            alert = alertBuilder.create();
	        	alert.show();
                break;
            case 2: 
	            alertBuilder.setMessage("Connection to product database timed out.  Try again later.");
	        	alert = alertBuilder.create();
	        	alert.show();
                break;
            case 3: 
	            alertBuilder.setMessage("Unsupported character in barcode.  Check barcode and try again.");
	            alert = alertBuilder.create();
	        	alert.show();
                break;
            case 4: 
            	alertBuilder.setMessage("No product found for barcode "+barcode+" in product database.");
            	alert = alertBuilder.create();
            	alert.show();
            	break;
            default: System.out.println("Oops, something unexpected happened.");
                    break;
            }
    }
    
    
    @Override
    public Integer doInBackground(String... args) {
    	barcode = args[0];
    	loc = args[2];
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();  
        pairs.add(new BasicNameValuePair("barcode", args[0]));
        String filepath = args[1]+"/"+args[0];
    //public void getData(String contents, String path){
	    try {
	    	httpClient = new DefaultHttpClient();
	        // set timeout 3 seconds this may require changing
	        HttpConnectionParams.setSoTimeout(httpClient.getParams(), 7000);
	        
	    	if(loc == "main"){
	        //Connect to server for product info
		        String url = "http://118.208.126.168:81/cpt/phpappfixed/product.php";
		        HttpPost httpPost = new HttpPost(url);
		        httpPost.setEntity(new UrlEncodedFormEntity(pairs));
		        HttpResponse response = null;
		        response = httpClient.execute(httpPost);
		        //Get response from server
		        String product = "";
		        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		                ByteArrayOutputStream os = new ByteArrayOutputStream();
		                response.getEntity().writeTo(os);
		                product = os.toString();
		                if(product.isEmpty() || product.equals("null")) {
		                	safeClose(httpClient);
		                	return 4;
		                }
		        }else {
		        	safeClose(httpClient);
		        	return 1;
		        }
		        
		//                  System.out.println(product);
		        
		        //Connect to server for manufacturer info
		        String url2 = "http://118.208.126.168:81/cpt/phpappfixed/manufacturer.php";
		        HttpPost post2 = new HttpPost(url2);  
		        //List<NameValuePair> pairs2 = new ArrayList<NameValuePair>();  
		        //pairs2.add(new BasicNameValuePair("barcode", contents));
		        post2.setEntity(new UrlEncodedFormEntity(pairs));
		        HttpResponse response2 = httpClient.execute(post2);  
		        
		        //Get response from server
		        String manufacturer = "";
		        if (response2.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		                ByteArrayOutputStream os2 = new ByteArrayOutputStream();
		                response2.getEntity().writeTo(os2);
		                manufacturer = os2.toString();
		                if(manufacturer.isEmpty() || manufacturer.equals("null")) {
		                	safeClose(httpClient);
		                	return 4;
		                }
		        }else {
		        	safeClose(httpClient);
		        	return 1;
		        }
		        
		      //Connect to server for manufacturer info
		        String url3 = "http://118.208.126.168:81/cpt/phpappfixed/location.php";
		        HttpPost post3 = new HttpPost(url3);  
		        //List<NameValuePair> pairs2 = new ArrayList<NameValuePair>();  
		        //pairs2.add(new BasicNameValuePair("barcode", contents));
		        post3.setEntity(new UrlEncodedFormEntity(pairs));
		        HttpResponse response3 = httpClient.execute(post3);
		        
		        //Get response from server
		        String location = "";
		        if (response3.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		                HttpEntity resEntityGet = response3.getEntity(); 
		                if (resEntityGet != null) {  
		                    location = EntityUtils.toString(resEntityGet);
		                    if(location.isEmpty() || location.equals("null")) {
			                	safeClose(httpClient);
			                	return 4;
			                }
		//                      System.out.println(location);
		                }
		        }else {
		        	safeClose(httpClient);
		        	return 1;
		        }
		        
		              //Connect to server for manufacturer info
		        String url4 = "http://118.208.126.168:81/cpt/phpappfixed/allergen.php";
		        HttpPost post4 = new HttpPost(url4);  
		        //List<NameValuePair> pairs2 = new ArrayList<NameValuePair>();  
		        //pairs2.add(new BasicNameValuePair("barcode", contents));
		        post4.setEntity(new UrlEncodedFormEntity(pairs));
		        HttpResponse response4 = httpClient.execute(post4);
		        
		        //Get response from server
		        String allergen = "";
		        if (response4.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		                HttpEntity resEntityGet2 = response4.getEntity(); 
		                if (resEntityGet2 != null) {  
		                    allergen = EntityUtils.toString(resEntityGet2);
		//                      System.out.println(allergen);
		                }
		        }else {
		        	safeClose(httpClient);
		        	return 1;
		        }
		                       
		
		        //Write json into file
		        FileWriter pfile = new FileWriter(filepath+"product.json");
		        JSONObject p = new JSONObject(product);
		        pfile.write(p.toString());
		        pfile.flush();
		        pfile.close();
		        
		        //Write json into file
		        FileWriter mfile = new FileWriter(filepath+"manufacturer.json");
		        JSONObject m = new JSONObject(manufacturer);
		        mfile.write(m.toString());
		        mfile.flush();
		        mfile.close();
		        
		        
		        //Write json into file
		        FileWriter lfile = new FileWriter(filepath+"location.json");
		        JSONArray l = new JSONArray(location);
		        //System.out.println(l);
		        System.out.println(l.toString());
		        lfile.write(l.toString());
		        lfile.flush();
		        lfile.close();
		        
		        FileWriter afile = new FileWriter(filepath+"allergen.json");
		        if(!allergen.equals("null")) {
		        	//Write json into file
		            JSONArray a = new JSONArray(allergen);
		            //System.out.println(l);
		            System.out.println(a.toString());
		            afile.write(a.toString());
		            afile.flush();
		        }
		        afile.close();
	    	}
	        if (loc == "comment") {
		        //Connect to server for manufacturer info
		  		String url5 = "http://118.208.126.168:81/cpt/phpappfixed/comment.php"; 
		  		HttpPost post5 = new HttpPost(url5);  
		  		//List<NameValuePair> pairs2 = new ArrayList<NameValuePair>();  
		  		//pairs2.add(new BasicNameValuePair("barcode", contents));
		  		post5.setEntity(new UrlEncodedFormEntity(pairs));
		  		HttpResponse response5 = httpClient.execute(post5);
		  		
		  		//Get response from server
		  		String comment = "";
		  		if (response5.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		  		    HttpEntity resEntityGet3 = response5.getEntity(); 
		  		    if (resEntityGet3 != null) {  
		  		    	comment = EntityUtils.toString(resEntityGet3);
		  		    	System.out.println(comment);
		  		    }
		  		}else {
		  			safeClose(httpClient);
		          	return 1;
		  		}
		  		safeClose(httpClient);
				//Write json into file
				FileWriter cfile = new FileWriter(filepath+"comment.json");
				if(!comment.equals("null")) {
					JSONArray c = new JSONArray(comment);
					//System.out.println(l);
					System.out.println("lovecomments"+c.toString());
					cfile.write(c.toString());
					cfile.flush();
				}
				cfile.close();
	        }
	        
	        if(loc == "mcomment"){
	        	
	    		//Connect to server for manufacturer info
	    		String url6 = "http://118.208.126.168:81/cpt/phpappfixed/manufacturerComment.php"; 
	    		HttpPost post6 = new HttpPost(url6);  
	    		//List<NameValuePair> pairs2 = new ArrayList<NameValuePair>();  
	    		//pairs2.add(new BasicNameValuePair("barcode", contents));
	    		post6.setEntity(new UrlEncodedFormEntity(pairs));
	    		HttpResponse response6 = httpClient.execute(post6);
	    		
	    		//Get response from server
	    		String mcomment = "";
	    		if (response6.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	    		    HttpEntity resEntityGet4 = response6.getEntity(); 
	    		    if (resEntityGet4 != null) {  
	    		    	mcomment = EntityUtils.toString(resEntityGet4);
	    		    	System.out.println(mcomment);
	    		    }
	    		}else {
	    			safeClose(httpClient);
	            	return 1;
	            }
	    		safeClose(httpClient);
				//Write json into file
				FileWriter mcfile = new FileWriter(filepath+"mcomment.json");
				if(!mcomment.equals("null")) {
					JSONArray mc = new JSONArray(mcomment);
					//System.out.println(l);
					System.out.println(mc.toString());
					mcfile.write(mc.toString());
					mcfile.flush();
				}
				mcfile.close();
	        }
	
	    } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
	    	safeClose(httpClient);
            System.out.println("Unsupported");
            e1.printStackTrace();
            return 3;
	    } catch (IOException e) {
	    	safeClose(httpClient);
            System.out.println("I/O exception accessing database");
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 1;
	    } catch (JSONException e) {
	    	safeClose(httpClient);
            System.out.println("JSON exception accessing database");
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 4;
            
	    }
	    
	    return 0;
    	//ConnectionManager.getInstance().didComplete(this);
    }
    
    private void safeClose(HttpClient client) {
        if(client != null && client.getConnectionManager() != null)
        {
            client.getConnectionManager().shutdown();
        }
    }
    
}
